﻿namespace MDK.Device.Devices
{
    public class PlcDevice : IPlcDevice
    {
        private PlcAddress _scramAddr = new PlcAddress("M14");
        private PlcAddress _clearErrorAddr = new PlcAddress("M7");
        private PlcAddress _autoModeAddr = new PlcAddress("M11");
        private PlcAddress _manualModeAddr = new PlcAddress("M10");
        private PlcAddress _startAutoModeAddr = new PlcAddress("M12");
        private PlcAddress _stopAutoModeAddr = new PlcAddress("M13");
        private PlcAddress _autoModeReadyAddr = new PlcAddress("M15");

        public IPlc PLC { get; }

        public PlcDevice(IPlc plc)
        {
            PLC = plc;
        }

        public bool IsScrammed
        {
            get
            {
                return !PLC.BitIsSet(_scramAddr);
            }
        }

        public void SwitchAutoMode()
        {
            PLC.ResetBit(_manualModeAddr);
            PLC.SetBit(_autoModeAddr);
            PLC.ResetBit(_startAutoModeAddr);
            PLC.ResetBit(_stopAutoModeAddr);
            PLC.SetBit(_startAutoModeAddr);
        }

        public void SwitchManualMode()
        {
            PLC.ResetBit(_autoModeAddr);
            PLC.SetBit(_manualModeAddr);
            PLC.ResetBit(_startAutoModeAddr);
            PLC.ResetBit(_stopAutoModeAddr);
            PLC.SetBit(_stopAutoModeAddr);
        }

        public void ClearError()
        {
            PLC.ResetBit(_clearErrorAddr);
            PLC.SetBit(_clearErrorAddr);
            PLC.ResetBit(_clearErrorAddr);
        }

        public bool IsAutoMode
        {
            get { return PLC.BitIsSet(_autoModeReadyAddr); }
        }

        public bool IsManualMode
        {
            get { return PLC.BitIsSet(_manualModeAddr); }
        }
    }
}